package com.peanut.web.exception;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.peanut.util.operation.OperationResult;
import com.peanut.util.operation.StatusCode;

/**
 * 全局异常处理类
 * 
 * @author jzsong@uworks.cc
 */
public class ExceptionResolver extends SimpleMappingExceptionResolver {

  @Override
  protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
      Exception ex) {
    String errorMessage = ex.getMessage();
    logger.info("系统异常：" + errorMessage);
    try {
      String viewName = determineViewName(ex, request);
      // 若能找到 返回网页的地址
      if (viewName != null) {
        String accept = request.getHeader("accept");
        String xRequestedWith = request.getHeader("X-Requested-With");
        // 如果不是异步请求
        if (accept.indexOf(MediaType.APPLICATION_JSON_VALUE) < 0
            || (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") < 0)) {
          Integer statusCodes = determineStatusCode(request, viewName);
          if (statusCodes != null) {
            applyStatusCodeIfPossible(request, response, statusCodes);
          }
          request.setAttribute("exceptionMsg", OperationResult.fail(errorMessage, StatusCode.SYSTEM_ERROR.code));
          return getModelAndView(viewName, ex, request);
        }
        // 异步请求
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(OperationResult.fail(StatusCode.SYSTEM_ERROR));
        printWriter.flush();
        printWriter.close();
        return new ModelAndView();
      }

      // 返回JSON的数据格式
      response.setContentType("application/json;charset=UTF-8");
      PrintWriter printWriter = response.getWriter();
      if (ex.toString().indexOf("mysql.") > -1) {
        printWriter.write(OperationResult.fail(StatusCode.SYSTEM_DATA_ERROR));
      } else {
        printWriter.write(OperationResult.fail(StatusCode.SYSTEM_ERROR));
      }
      printWriter.flush();
      printWriter.close();
    } catch (Exception e) {
      logger.info(e.getMessage());
    }
    return new ModelAndView();
  }

}
